package net.hashcoding.cookbook.core;

import net.hashcoding.cookbook.core.controller.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/6/24.
 */
public abstract class Application extends BaseServlet {

    @Override
    protected void initialize() {
        setupService();
        setupRoute();
    }

    protected abstract void setupRoute();

    protected abstract void setupService();

    @Override
    protected void dispatch(HttpMethod method, HttpServletRequest request, HttpServletResponse response) {
        try {
            dispatchInternal(method, request, response);
        } catch (ServiceException e) {
            try {
                response.sendError(e.getCode(), e.getVerbose());
            } catch (IOException ignore) {
                // ignore
            }
        }
    }

    private void dispatchInternal(HttpMethod method, HttpServletRequest request, HttpServletResponse response) {

        HashMap<String, Object> environment = new HashMap<>();
        request = Service.process(environment, request);

        Controller controller = Router.redirect(request);
        if (controller == null) {
            throw ServiceException.notFound();
        }

        HttpServletRequest finalRequest = request;
        Controller.transaction(environment,
                () -> controller.service(method, finalRequest, response));
    }
}
